﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Consul.Console
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine("Test Consul");
            ConsulClient client = new ConsulClient(c => c.Address = new Uri("http://127.0.0.1:8500"));

            var response = client.Agent.Services().Result.Response;

            //服务名称区分大小写，若要不区分：Equals(serviceName, StringComparison.OrdinalIgnoreCase)
            var serviceList = response
                .Where(s => s.Value.Service.Equals("test.consul"))
                .Select(s => s.Value).ToList();

            foreach (var item in serviceList)
            {
                System.Console.WriteLine(item.Address + ":" + item.Port);
            }

            System.Console.ReadKey();
        }
    }
    /// <summary>
    /// 轮询负载均衡算法
    /// </summary>
    public static class RoundRobin
    {
        private static object obj = new object();

        static Dictionary<string, int> dic = new Dictionary<string, int>
        {
            { "192.168.1.12", 1},
            {"192.168.1.13", 1 },
            { "192.168.1.14", 3},
            { "192.168.1.15", 1},
            {"192.168.1.16", 1},
            {"192.168.1.17", 1 },
            { "192.168.1.18", 1},
            { "192.168.1.19", 1}
        };

        static int pos = 0;
        public static string roundRobin()
        {
            var keyList = dic.Keys.ToList();

            string server = null;

            lock (obj)
            {
                if (pos >= keyList.Count)
                {
                    pos = 0;
                }
                server = keyList[pos];
                pos++;
            }
            return server;
        }
    }

}
